package com.withoutwords.ui;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gcm.GCMRegistrar;
import com.withoutwords.engine.Game;
import com.withoutwords.engine.GameController;
import com.withoutwords.engine.comminication.CommunicationManager;
import com.withoutwords.engine.comminication.IServerResultListener;
import com.withoutwords.engine.comminication.ServerRequests;
import com.withoutwords.engine.settings.Settings;
import com.withoutwords.engine.social.ISocialNetworkController;
import com.withoutwords.engine.social.SocialEngine;
import com.withoutwords.engine.social.SocialNetwork;
import com.withoutwords.engine.social.SocialUser;
import com.withoutwords.engine.social.listeners.ISocialFriendListListener;
import com.withoutwords.ui.custom.GamesExpandableListAdapter;
import com.withoutwords.GCMIntentService;
import com.withoutwords.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.TextView;

public class WithoutWordsActivity extends BaseActivity implements OnClickListener,
		IServerResultListener, OnGroupClickListener, ISocialFriendListListener {

	GamesExpandableListAdapter listAdapter;
	CommunicationManager CommMgrInstance;
	ISocialNetworkController fbController;
	Handler uihandler;

	Handler joinGameHandler;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Initialize settings prefrences
		Settings settings = Settings.getInstance();
		settings.setPrefrences(this.getApplication().getSharedPreferences(
				"User", Activity.MODE_PRIVATE));

		try
		{
		// push notification init
		GCMRegistrar.checkDevice(this.getApplicationContext());
		GCMRegistrar.checkManifest(this.getApplicationContext());
		final String regId = GCMRegistrar.getRegistrationId(this);
		if (regId.equals("")) {
			GCMRegistrar
					.register(this.getApplicationContext(), GCMIntentService.SenderID);
		} else {
			Settings.getInstance().setPushToken(regId);
		}
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		
		GameController.getInstance().setApplicatoinContext(getApplicationContext());
		
		// check if user is logged in
				if (!SocialEngine.getSocialEngine().isLoggenIn(this) ) {
					startActivity(new Intent(getApplicationContext(),
							LoginActivity.class));
					finish();
				}
				
		// ui init
		Button btn = (Button) findViewById(R.id.btnInvite);
		btn.setOnClickListener(this);

		btn = (Button) findViewById(R.id.btnCreateGame);
		btn.setOnClickListener(this);

		// ////////////////////////////////////////////////

		
	

		// /initialize handlers
		uihandler = new Handler();
		joinGameHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {

				super.handleMessage(msg);
				Bundle data = msg.getData();
				Game game = (Game) data.get("game");
				GameController.getInstance().joinGame(game);
			//	finish();
			}
		};

	}

	
	
	@Override
	protected void onStart() {

		TextView emptyView = new TextView(this);
		emptyView.setText(getString(R.string.loading_friends_games));

		final ExpandableListView exList = (ExpandableListView) findViewById(R.id.lstFriendsGames);
		exList.setEmptyView(emptyView);
		/*
		 * exList.setGroupIndicator(null); exList.setOnGroupClickListener(new
		 * OnGroupClickListener() {
		 * 
		 * @Override public boolean onGroupClick(ExpandableListView parent, View
		 * v, int groupPosition, long id) { exList.expandGroup(groupPosition);
		 * return false; } });
		 */

		fbController = SocialEngine.getSocialEngine()
				.getSocialNetworkController(SocialNetwork.Facebook);
		fbController.readFriendList(this, true);

		super.onStart();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnInvite: {
			ISocialNetworkController fbController = SocialEngine
					.getSocialEngine().getSocialNetworkController(
							SocialNetwork.Facebook);
			fbController.inviteFriends(this, "Play with me");
			break;
		}
		case R.id.btnCreateGame: {
			startActivity(new Intent(getApplicationContext(),
					CreateGameActivity.class));
			break;
		}
		}
	}

	@Override
	public void onRequestSucceed(ServerRequests serverRequest,
			final Bundle response) {

		uihandler.post(new Runnable() {

			@Override
			public void run() {

				// initialize empty list
				listAdapter = new GamesExpandableListAdapter(
						WithoutWordsActivity.this, joinGameHandler);
				Object ooo = response.getSerializable("games");
				listAdapter.setGames((ArrayList<Game>) ooo);
				ExpandableListView exList = (ExpandableListView) findViewById(R.id.lstFriendsGames);
				exList.setAdapter(listAdapter);
				exList.expandGroup(0);
				// listAdapter.notifyDataSetInvalidated();
			}
		});

	}

	@Override
	public void onRequestFailed(ServerRequests serverRequest, String error) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
		Game selectedGame = listAdapter.getGameAt(groupPosition);
		Intent intent = new Intent(this,ViewerPlayingActivity.class);
		intent.putExtra("gamejoined", false);
		intent.putExtra("game", selectedGame);
		startActivity(intent);
		//GameController.getInstance().joinGame(selectedGame);
		// finish();
		return false;
	}

	@Override
	public void onError(String Error) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onFriendListRecieved(ArrayList<SocialUser> friends) {
		Bundle bundle = new Bundle();
		JSONArray arrayJson = new JSONArray();
		for (int i = 0; i < friends.size(); i++) {
			try {
				arrayJson.put(i, friends.get(i).toJSON());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		JSONObject obj = new JSONObject();
		try {
			obj.put(CommunicationManager.usersCode, arrayJson);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String objStr = obj.toString();
		bundle.putString(CommunicationManager.usersCode,
				objStr);
		// read games
		CommMgrInstance = CommunicationManager.getCommnuicationManager();
		CommMgrInstance.request(ServerRequests.getUserGames, bundle, this);
		//CommMgrInstance.request(ServerRequests.getPlayingUser, bundle, this);

	}
}